<?php

namespace App\Http\Requests\Admin\CollTown;

use App\Http\Requests\Request;
use App\Models\Common\CollTown;
use Validator;

class CreateRequest extends Request{
    public function authorize(){
        return true;
    }

    public function rules(){
        //添加编码判断
        Validator::extend('check_town_cid', function($attribute, $value, $parameters){
            $pid = $parameters[0];
            if(substr($value, 0, 6) != $pid){
                return false;
            }else{
                return true;
            }
        });
        //添加省份排序判断
        Validator::extend('check_town_sort', function($attribute, $value, $parameters){
            $pid = $parameters[0];
            if($value != 0){
                $CollTownSort = CollTown::where('pid', $pid)->pluck('sort')->toArray();
                if(in_array($value, $CollTownSort)){
                    return false;
                }else{
                    return true;
                }
            }else{
                return true;
            }
        });
        return [
            'province' => 'required',
            'area' => 'required',
            'city' => 'required',
            'name' => 'required',
            'en_name'=>'required',
            'cid' => 'required|integer|max:99999999|min:10000000|unique:coll_town,cid|check_town_cid:' . $this->pid,
            'pid' => 'required|integer',
            'longitude' => 'required|numeric',
            'latitude' => 'required|numeric',
            'sort' => 'check_town_sort:' . $this->pid
        ];
    }

    public function messages(){
        return [
            'province.required' => '省份必须选择',
            'area.required' => '地级市必须选择',
            'city.required' => '县/市/区必须选择',
            'name.required' => '地标名称必须填写',
            'en_name.required' => '英文名称必须填写',
            'cid.required' => '地标编码必须填写',
            'cid.integer' => '地标编码必须是一个整数',
            'cid.max' => '地标编号必须以当前县市区开头的8位数',
            'cid.min' => '地标编号必须以当前县市区开头的8位数',
            'cid.unique' => '地标编码已经存在',
            'cid.check_town_cid' => '地标编码和县级市不匹配',
            'pid.required' => '地标父级编码必须填写',
            'pid.integer' => '地标父级编码必须是一个整数',
            'longitude.required' => '地标经度不能为空',
            'longitude.numeric' => '地标经度必须是一个数值',
            'latitude.required' => '地标纬度不能为空',
            'latitude.numeric' => '地标纬度必须是一个数值',
            'sort.check_town_sort' => '地标排序已经存在'
        ];
    }
}